<template>
    <!-- 入库弹窗 -->
    <el-dialog v-model="props.dialogFormVisible" title="Shipping address" width="60%" :before-close="cancelRuKu"
        :close-on-click-modal=false>
        <template #header>
            <span>请确认</span>
        </template>
        <div style="color: #fff;">
            <!-- 您要入库的是：<span v-for="(item, index) in rowInfo" :key="index">{{ item.bookName + ',' }}</span> -->
            <span>您要入库的是：</span>
            <div style="margin-left: 1vw;">
                <div>资料名称：{{ rowInfo[0]&&rowInfo[0].bookName }}</div>
                <div>出版日期：{{ rowInfo[0]&&rowInfo[0].publishTime }}</div>
                <div>密级：{{ rowInfo[0]&&rowInfo[0].miji }}</div>
            </div>  
        </div>
        <div class="store-posi">
            <span class="sp">存放位置：{{ recommendBox }}</span> <el-button type="primary" link
                @click="chooseBox">自定义位置</el-button>
        </div>
        <div style="color: #fff;margin-left: 1vw;">
            本次入库数量:{{ rowInfo.length }}
        </div>
        <el-table class="my-custom-table" :data="suggestBox" border style="width: 100%" v-if="suggestBox.length > 1" :key="toggleRender">
            <el-table-column align="center" prop="cabinetName" label="推荐柜子" width="220" />
            <el-table-column align="center" prop="remainingCapacity" label="柜子容量" width="120" />
            <el-table-column align="center" label="扫码">
                <template #default="{ row }">
                    <div class="operation-btns">
                        <el-button-group>
                            <el-button type="primary" size="small" style="width: 10vw;" plain
                                @click="activeAndScan(row)">
                                {{ row.active ? '请扫码' : '点击扫码' }}
                            </el-button>
                            <el-button type="primary" size="small" plain @click="deleteCurrentScan(row)">{{
                                row.codeLength }}</el-button>
                        </el-button-group>
                    </div>
                </template>
            </el-table-column>
            <el-table-column align="center" fixed="right" label="操作" width="120">
                <template #default="{ row }">
                    <el-button type="text" @click="deleteRow(row)" size="small">清空</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-table class="my-custom-table" :data="suggestBox" border style="width: 100%" v-else>
            <el-table-column align="center" prop="cabinetName" label="推荐柜子" />
            <el-table-column align="center" prop="remainingCapacity" label="柜子容量" />
        </el-table>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="confirmRuku">确定</el-button>
                <el-button type="primary" @click="cancelRuKu"> 取消 </el-button>
            </div>
        </template>
    </el-dialog>
    <selectBox :isShow="showBox" @choosedBox="closeBoxSelected" :rows="rowInfo" @close="closeBoxOnly"
        :isMulity="rowInfo.length > 1" />
</template>
<script lang="ts" setup>
import { reactive, ref, watch } from 'vue'
import selectBox from './selectBox.vue';
import { recommendCabinet, addInStock, judgeCode ,definiteOpening} from '../../../../../api/index'
import { ElMessage } from 'element-plus';
const props = defineProps<{ dialogFormVisible: boolean, rowInfo: any[] }>();
const emit = defineEmits(['closeForm', 'confirmRuKu']);
let showBox = ref(false);

let toggleRender = ref(new Date().getTime());

// 打开柜信息
let rukuInfo = reactive<any>({});
watch(() => props.dialogFormVisible, (newVal) => {
    if (newVal) {
        recommend();
        rukuInfo = props.rowInfo;

    }
})

// 推荐柜子
let suggestBox = reactive<any>([]);

// 推荐柜子文字
let recommendBox = ref('');

// 扫码输入框
let input = reactive<any>({});

const chooseBox = () => {
    showBox.value = true;
}
// 确定入库
const confirmRuku = () => {
    console.log(suggestBox);
    
    // TODO
    // 发送入库请求
    if (suggestBox.length == 1) {
        // const params = { bookId: props.rowInfo[0].bookId, cabinetId: suggestBox[0].cabinetId, drawerId: suggestBox[0].drawerId };
        const params = [{
            bookId: props.rowInfo[0].bookId,
            // 资料柜id
            cabinetId: suggestBox[0].cabinetId,
            // 抽屉id
            drawerId: suggestBox[0].drawerId,
            barCodes: rukuInfo.map((el: any) => {
                return el.code
            })
        }]
        // 直接入库
        addInStock(params).then((res: any) => {
            if (res.code === 200) {
                ElMessage.success('入库成功');
                // definiteOpening()
                suggestBox.forEach((el:any) => {
                    definiteOpening({region:el.region,arrange:el.arrange,joint:el.joint,storey:el.storey,side:el.side,ipAddress:el.ipAddress});
                });
                emit('confirmRuKu', suggestBox);
            } else {
                ElMessage.error(res.msg);
            }
        })
    } else {
        let readyBox = suggestBox.filter((el: any) => el.codes.length > 0);
        const params = readyBox.map((el: any) => {
            return {
                bookId: props.rowInfo[0].bookId,
                // 资料柜id
                cabinetId: el.cabinetId,
                // 抽屉id
                drawerId: el.drawerId,
                barCodes: el.codes
            }
        })
        // console.log(params);

        addInStock(params).then((res: any) => {
            if (res.code == 200) {
                ElMessage.success('入库成功');
                suggestBox.forEach((el:any) => {
                    definiteOpening({joint:el.joint,storey:el.storey,side:el.side,ipAddress:el.ipAddress});
                });
                emit('confirmRuKu', readyBox);
            } else {
                ElMessage.error(res.msg);
            }
        })
        // emit('confirmRuKu', readyBox);
    }
}
// 取消入库
const cancelRuKu = () => {
    emit('closeForm');
}
const deleteRow = (row: any) => {
    suggestBox.splice(suggestBox.findIndex((el: any) => el.drawerId == row.drawerId), 1);
    toggleRender.value = new Date().getTime();
}
// 选中图书后
const closeBoxSelected = (val: any) => {
    const pos = JSON.parse(JSON.stringify(val));
    suggestBox = pos.map((el: any) => {
        el.codes = [];
        el.codeLength = 0;
        el.active = false;
        el.cabinetName = el.cabinetName + (el.side == '1' ? '左面' : '右面') + el.joint + '节' + el.storey + '层';
        el.orgName = props.rowInfo[0].orgName;
        el.miji = props.rowInfo[0].miji;
        return el;
    });
    recommendBox.value = pos.map((po: any) => {
        return po.cabinetName + (po.side == '1' ? '左面' : '右面') + po.joint + '节' + po.storey + '层'
    }).join(',');
    showBox.value = false
}

// 仅关闭box
const closeBoxOnly = () => {
    showBox.value = false;
}
// 查询推荐柜子
const recommend = async () => {
    let res = await recommendCabinet({ bookId: props.rowInfo[0].bookId, unWarehouseNum: props.rowInfo.length });
    console.log(res.data);
    console.log( props.rowInfo)
    
    if (res.data.length > 1) {
        suggestBox = res.data.map((el: any) => {
            el.orgName = props.rowInfo[0].orgName;
            el.miji = props.rowInfo[0].miji;
            el.codes = []
            return el;
        });
    } else {
        suggestBox = res.data.map((el: any) => {
            el.orgName = props.rowInfo[0].orgName;
            el.miji = props.rowInfo[0].miji;
            return el;
        });
    }
    recommendBox.value = res.data.map((el: any) => el.cabinetName).join(',');
}

// 扫码
const activeAndScan = (row: any) => {
    suggestBox.map((el: any) => {
        if (el.drawerId === row.drawerId) {
            el.active = !el.active;
        } else {
            el.active = false
        }
        toggleRender.value = new Date().getTime();
        return el;
    });
    const inputs = JSON.parse(JSON.stringify(input));
    if (Object.keys(inputs).length > 0) {
        input.removeEventListener('keyup', (e: any) => {
            getCode(e, row, '')
        });
        document.body.removeChild(input);
        input = null;
    }
    input = document.createElement('input');
    document.body.appendChild(input);
    input.style.position = 'fixed';
    input.style.width = '0';
    input.style.height = '0';
    input.style.border = '0';
    input.style.padding = '0';
    input.style.margin = '0';
    input.focus();
    input.addEventListener('keyup', (e: any) => {
        const val = input.value;
        // input.value = '';
        getCode(e, row, val)
    })
}
// 获取扫码结果，做输入事件处理
const getCode = async (e: any, row: any, val: any) => {
    if (e.keyCode === 13 || e.which === 13) {
        let tables = suggestBox.find((el: any) => el.drawerId === row.drawerId);
        if (tables.scanNUm >= tables.remainingCapacity) {
            ElMessage.error('当前柜子已满，请选择其他柜子');
        } else {
            // TODO前端暂时不做校验，直接添加
            const code = val;
            let coded = suggestBox.find((el:any)=>el.codes.includes(code));
            let counts = suggestBox.reduce((prev:any,curr:any)=>{
                prev+=curr.codes.length;
                return prev}
            ,0)
            
            if(coded) {
                input.value = '';
                ElMessage.error('该条码已存在');
                return;
            }
            if(counts>=props.rowInfo.length){
                ElMessage.error('扫码数量已达到入库数量');
                return;
            }
            let isScaned = await judgeCode({ bookId: props.rowInfo[0].bookId, barCode: code }) as any;
            if (isScaned.code === 200) {
                if (isScaned.data) {
                    tables.codes.push(code);
                    tables.codeLength = tables.codes.length;
                    tables = Object.assign({}, tables);
                    ElMessage.success(isScaned.msg);
                    toggleRender.value = new Date().getTime();
                } else {
                    input.value = '';
                    ElMessage.error(isScaned.msg);
                }
            } else {
                input.value = '';
                ElMessage.error(isScaned.msg);
            }
        }
    }
}

// TODO删除条码
const deleteCurrentScan = (row: any) => {
    console.log(row);
    
 }

</script>
<style lang="less">
.store-posi {
    color: #fff;
    margin-left: 1vw;
    display: flex;
    align-items: center;

    .sp {
        margin-right: 10px;
    }
}
</style>